import request from '@/utils/request'
import qs from 'qs'
import { message } from 'ant-design-vue'

// 封装request
export function fetch(requestParams){
  if(requestParams.method === 'post' || requestParams.method === 'put'){
    return request({
      url: requestParams.url,
      method: requestParams.method,
      data: requestParams.data
    })
  }
  if(requestParams.method === 'get' || requestParams.method === 'delete'){
    let queryString = qs.stringify(requestParams.data)
    return request({
      url: requestParams.url+(queryString.length > 0 ? '?'+queryString : ''),
      method: requestParams.method,
    })
  }
}

// 上传文件
export function fetchUpload(url,formData){
  return new Promise((resolve,reject)=>{
    // 使用 axios 发送 FormData
    request.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data' // 确保服务端能正确解析 FormData
      }
    }).then((res)=>{
      if(res.code === 500){
        reject(new Error('上传失败'))
      }
      resolve(res)
    }).catch((err)=>{
      console.log('err',err)
      reject(new Error('上传失败'))
    })
  })
}

// 下载文件
export function fetchDownload(url,params,fileName=''){
  message.loading({content:'正在下载中',duration:0,key:'downloadFile'})
  let queryString = qs.stringify(params)
  // 使用 axios 发送 FormData
  request({
    method: 'get',
    url: url+(queryString.length > 0 ? '?'+queryString : ''),
    responseType: 'blob'
  }).then((res)=>{
    console.log(res)
    message.destroy()
    const downloadURL = (window.URL || window.webkitURL).createObjectURL(res.data);
    console.log(downloadURL)
    // 创建a标签
    let a = document.createElement('a');
    // 下载后文件的名字
    const disposition = res.headers['content-disposition'];
    // 使用正则表达式提取文件名
    const filenameRegex = /filename="([^"]+)"/;
    const matches = filenameRegex.exec(disposition);
    const filename = matches ? matches[1] : null;

    // console.log(filename);
    a.download = fileName||filename||new Date().getTime().toString();
    a.href = downloadURL;
    document.body.appendChild(a);
    a.click();
    setTimeout(function () {
      // 移除内存中的临时文件路径和为下载而创建的a标签
      URL.revokeObjectURL(downloadURL);
      a.remove();
    }, 1000);
  }).catch((err)=>{
    message.destroy()
    message.error('下载失败')
  })
}
